<template>
  <div class="goods-detail-container">
    <div class="goods-gallery">
      <div class="main-image-container">
        <img
          :src="currentImage || product.goodsImg"
          :alt="product.name"
          class="main-image"
        />
      </div>
      <div class="thumbnails">
        <div
          v-for="(img, index) in product.picList"
          :key="index"
          @click="currentImage = img.picUrl"
          :class="['thumbnail', { active: currentImage === img.picUrl }]"
        >
          <img :src="img.picUrl" :alt="`商品图${index + 1}`" />
        </div>
      </div>
    </div>

    <div class="goods-info">
      <h1 class="goods-title">{{ product.name }}</h1>

      <div class="price-section">
        <span class="current-price">¥{{ product.price }}</span>
        <span class="original-price" v-if="product.goodsMktprice">
          原价: ¥{{ product.goodsMktprice }}
        </span>
        <span class="total-price" v-if="quantity > 1">
          小计: ¥{{ (product.price * quantity).toFixed(2) }}
        </span>
      </div>
      <div class="spec-section" v-if="specList && specList.length > 0">
        <div v-for="spec in specList" :key="spec.specId" class="spec-item">
          <h3 class="spec-title">{{ spec.specName }}</h3>
          <div class="spec-options">
            <el-radio-group v-model="selectedSpecs[spec.specId]">
              <el-radio
                v-for="option in spec.specValueList"
                :key="option.valueId"
                :label="option.valueId"
                :disabled="option.status === 0"
              >
                {{ option.value }}
              </el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      <div class="description-section">
        <div class="desc-content" v-html="product.description"></div>
      </div>

      <div class="quantity-section">
        <h3 class="quantity-title">数量</h3>
        <div class="quantity-control">
          <button class="quantity-btn" @click="decreaseQuantity">-</button>
          <input
            type="number"
            v-model.number="quantity"
            min="1"
            :max="product.store"
            class="quantity-input"
            @change="handleQuantityChange"
          />
          <button class="quantity-btn" @click="increaseQuantity">+</button>
        </div>
        <span class="stock-info">库存 {{ product.store }} 件</span>
      </div>

      <div class="action-buttons">
        <button class="btn btn-buy" @click="buyNow">立即购买</button>
        <button class="btn btn-cart" @click="addToCart">加入购物车</button>
      </div>
    </div>

    <div class="goods-details" v-if="product.details">
      <div class="detail-content" v-html="product.details"></div>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { getGoodsDetail } from "@/api";

export default {
  name: "GoodsDetail",
  data() {
    return {
      loading: false,
      error: null,
      product: {
        goodsImg: "",
        picList: [],
        name: "",
        price: 0,
        store: 0,
        description: "",
        details: "",
      },
      specList: [],
      currentImage: null,
      quantity: 1,
      selectedSpecs: {},
    };
  },
  created() {
    this.fetchGoodsDetail();
  },
  methods: {
    ...mapActions(["ADD_TO_CART"]),

    async fetchGoodsDetail() {
      try {
        this.loading = true;
        const { code, result } = await getGoodsDetail({
          id: this.$route.params.id,
          type: 0,
          cityId: 524,
        });

        if (code !== 200) throw new Error("获取商品数据失败");


        this.product = {
          ...result.goodsView,
          ...result.productView,
          id: result.productView.id,
        };

        // 处理规格数据
        this.specList = result.catSpecList || [];
        this.initSpecSelection();

        // 设置默认显示图片
        if (this.product.picList?.length) {
          this.currentImage = this.product.picList[0].picUrl;
        }
      } catch (error) {
        this.error = error.message || "加载商品详情失败";
      } finally {
        this.loading = false;
      }
    },

    initSpecSelection() {
      this.specList.forEach((spec) => {
        const selectedOption = spec.specValueList.find(
          (opt) => opt.status === 1
        );
        if (selectedOption) {
          this.$set(this.selectedSpecs, spec.specId, selectedOption.valueId);
        }
      });
    },

    getSelectedSpecText() {
      if (!this.specList.length) return "默认规格";

      return this.specList
        .map((spec) => {
          const selected = spec.specValueList.find(
            (opt) => opt.valueId === this.selectedSpecs[spec.specId]
          );
          return selected ? selected.value : "";
        })
        .filter(Boolean)
        .join(" / ");
    },

    addToCart() {
      const productToAdd = {
        id: this.product.id,
        name: this.product.name,
        price: this.product.price,
        image: this.product.goodsImg,
        spec: this.getSelectedSpecText(),
        quantity: this.quantity,
        stock: this.product.store,
      };

      this.ADD_TO_CART(productToAdd)
        .then(() => {
          this.$message.success("已成功加入购物车");
            this.$router.push("/shopping-car");
        })
        .catch((error) => {
          this.$message.error("加入购物车失败: " + error.message);
        });
    },

    buyNow() {
      this.addToCart();
      this.$router.push("/shopping-car");
    },

    increaseQuantity() {
      if (this.quantity < this.product.store) {
        this.quantity++;
      }
    },

    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },

    handleQuantityChange() {
      if (this.quantity < 1) {
        this.quantity = 1;
      } else if (this.quantity > this.product.store) {
        this.quantity = this.product.store;
      }
    },
  },
};
</script>

<style scoped>
.goods-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  background: #fff;
}

.goods-gallery {
  width: 480px;
  margin-right: 40px;
}

.main-image-container {
  width: 100%;
  height: 480px;
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.main-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.thumbnails {
  display: flex;
  gap: 10px;
  overflow-x: auto;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border: 1px solid #ddd;
  cursor: pointer;
  flex-shrink: 0;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail:hover,
.thumbnail.active {
  border-color: #f56c6c;
}

.goods-info {
  flex: 1;
  min-width: 300px;
}

.goods-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 15px 0;
}

.price-section {
  margin: 20px 0;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.current-price {
  font-size: 28px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 15px;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.total-price {
  margin-left: 15px;
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

.spec-section {
  margin: 20px 0;
}

.spec-item {
  margin-bottom: 15px;
}

.spec-title {
  font-size: 16px;
  color: #666;
  margin: 0 0 10px 0;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.description-section {
  margin: 20px 0;
  color: #666;
  line-height: 1.6;
}

.quantity-section {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.quantity-title {
  font-size: 16px;
  color: #666;
  margin-right: 20px;
}

.quantity-control {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background: #f9f9f9;
  font-size: 16px;
  cursor: pointer;
}

.quantity-input {
  width: 50px;
  height: 30px;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  border-left: none;
  border-right: none;
  text-align: center;
}

.stock-info {
  color: #666;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin: 30px 0;
}

.btn {
  flex: 1;
  padding: 12px 0;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-buy {
  background: #f56c6c;
  color: white;
}

.btn-buy:hover {
  background: #e05b5b;
}

.btn-cart {
  background: #409eff;
  color: white;
}

.btn-cart:hover {
  background: #3088e8;
}

.goods-details {
  width: 100%;
  margin-top: 40px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .goods-detail-container {
    flex-direction: column;
  }

  .goods-gallery {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
  }

  .main-image-container {
    height: 300px;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style>